package cn.edu.hpu.jie.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import cn.edu.hpu.jie.entity.Login;
import cn.edu.hpu.jie.util.RowMapping;
import cn.edu.hpu.jie.util.VoteDB;

public class LoginDao {
	private VoteDB<Login> db = new VoteDB<Login>();
	
	private class LoginMapping implements RowMapping<Login>{

		public Login getMapping(ResultSet rs) throws SQLException {
			Login l = new Login();
			l.setId(rs.getInt("id"));
			l.setIp(rs.getString("ip"));
			l.setNum(rs.getInt("num"));
			l.setTime(rs.getString("time"));
			l.setUserid(rs.getInt("userid"));
			return l;
		}
	}
	
	/**
	 * 插入登入记录
	 * @param l
	 * @return 记录的Id
	 */
	public int insertLogin(Login l) {
		String sql = "INSERT INTO t_login(ip, `time`, num, userid) VALUES (?, ?, ?, ?)";
		return db.getInsertPrimaryKey(sql, l.getIp(), l.getTime(), l.getNum(), l.getUserid());
	}
	
	/**
	 * 根据userid获取记录
	 * @param userid
	 * @return
	 */
	public Login getLastLogin(int userid) {
		String sql = "SELECT id, ip, `time`, num, userid FROM t_login WHERE userid = ? ORDER BY `time` DESC limit 1";
		return db.getObject(sql, new LoginMapping(), userid);
	}
	
	/**
	 * 获取所有记录或根据userid获取该用户的所有记录
	 * @param userid 可选
	 * @return
	 */
	public List<Login> getAllLogin(int...userid) {
		StringBuilder sb = new StringBuilder("SELECT id, ip, `time`, num, userid FROM t_login");
		if(userid.length != 0) {
			sb.append("WHERE id = ?");
		}
		return db.getAll(sb.toString(), new LoginMapping(), userid);
	}
}
